package com.Luoyi.springframework.beans.factory.support;

import com.Luoyi.springframework.beans.BeansException;
import com.Luoyi.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;


public class SimpleInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        //获取class
        Class clazz = beanDefinition.getBeanClass();
        try {
            if (ctor != null) {
                //如果有构建方法，交给 Constructor
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance();
            }else {
                //没有构建方法直接创建实例
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw  new BeansException("Failed to instance [" + clazz.getName() + "]",e);
        }
    }
}
